//
//  VOLAddHouseImageViewController.m
//  CameraAndAlbumTest
//
//  Created by administrator on 14-9-26.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLAddHouseImageViewController.h"
#import "VOLAppDelegate.h"
#import "common.h"

#import "BWJAddImageView.h"
#import "BWJImageCell.h"

@interface VOLAddHouseImageViewController ()
{
    VOLAppDelegate *del;
    NSMutableArray *deleteImages;
}

@end

@implementation VOLAddHouseImageViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"图片编辑";

    //
    del = kGetDel;
    //添加返回按钮
    addBackButton();
    
    //添加编辑按钮
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editImage:)];
    [right setTintColor:kThemeColor];
    self.navigationItem.rightBarButtonItem = right;
    
    
    //添加自定义控件
    NSArray *addnib = [[NSBundle mainBundle] loadNibNamed:@"BWJAddImageView" owner:self options:nil];
    BWJAddImageView *addImageView = addnib[0];
    //按钮添加动作
    [addImageView.addImageBtn addTarget:self action:@selector(addPhotos:) forControlEvents:UIControlEventTouchUpInside];
    
    [addImageView.addImageBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
    [addImageView.addImageBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    self.tableView.tableFooterView = addImageView;
    
    //允许同时编辑多个cell
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 刷新界面
-(void)viewWillAppear:(BOOL)animated{
    if (del.selectedHouseImages.count == 0) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
    else{
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
    
    //重新加载tableView
    [self.tableView reloadData];
}

#pragma mark 返回
-(void)goBack:(id)sender{
    back;
}

#pragma mark 编辑图片方法
-(void)editImage:(id)sender{
    if (deleteImages) {
        deleteImages = [NSMutableArray array];
    }
    
    BOOL result = !self.tableView.editing;
    if (result) {
        [self.tableView setEditing:result animated:YES];
        self.navigationItem.rightBarButtonItem.title = @"删除";
        NSLog(@"执行编辑");
    }else{
        self.navigationItem.rightBarButtonItem.title = @"编辑";
        NSLog(@"执行删除");
        [self deleteSelectedImages:sender];
        [self.tableView setEditing:result animated:YES];
    }
}

#pragma mark 删除图片
-(void)deleteSelectedImages:(id)sender{
    NSLog(@"delete");
    //获取被选中的cell的indexPath，
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
    if (selectedRows.count == 0) {
        return;
    }
    
    //删除数据
    NSMutableIndexSet *set = [NSMutableIndexSet new];
    
    for (NSIndexPath *indexPath in selectedRows) {
        [set addIndex:indexPath.row];
    }
    
    [del.selectedHouseImages removeObjectsAtIndexes:set];
    
    [self.tableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
    
    //如果del.selectedHouseImages中没有图片，编辑失效
    if (del.selectedHouseImages.count == 0) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}

#pragma mark 添加图片动作
-(void)addPhotos:(id)sender{
    NSLog(@"addimage");
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择照片", nil];
    [sheet showInView:self.view];
    
}


#pragma mark - actionsheet代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"照相");
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            //设置代理
            imagePicker.delegate = self;
            
            //判断是否有后置摄像头
            if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
                NSLog(@"没有摄像头");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//照相机
            
            //调用摄像头开始拍照
            [self presentViewController:imagePicker animated:YES completion:^{
                
            }];
            break;
        }
            
            
            
        case 1:
        {
            NSLog(@"选照片");
            //第一次使用时初始化这个数组
            if (!del.selectedHouseImages)
                del.selectedHouseImages = [[NSMutableArray alloc] init];
            
            //创建照片选取器
            ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
            picker.maximumNumberOfSelection = 10;
            picker.assetsFilter = [ALAssetsFilter allPhotos];
            picker.showEmptyGroups=NO;
            picker.delegate=self;
            picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
                if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                    NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                    return duration >= 5;
                } else {
                    return YES;
                }
            }];
            
            [self presentViewController:picker animated:YES completion:NULL];
        }
            
            break;
            
        case 2:
            NSLog(@"cancel");
            return;
            break;
            
            
    }
}



#pragma mark - UIImagePickerController代理方法，拍照结束后全调用这个方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取拍到的照片
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //将image转化成NSData,并加入到数组
    NSData *data = UIImageJPEGRepresentation(image, kCompressionRatio);
    [del.selectedHouseImages addObject:data];
    //图片加入数组后，将拍照这个界面关闭
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    
    //取出图片,并添加到数组
    NSMutableArray *willAddImages = [NSMutableArray array];
    
    for (int i = 0; i < assets.count; i++) {
        ALAsset *asset = assets[i];
        //获取图片，并将图片压缩后，转化成NSData加入到数组中
        UIImage *image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [willAddImages addObject:UIImageJPEGRepresentation(image, kCompressionRatio)];
        
    }
    
    
    
    //查检图片是否有重复的
    NSArray *resultArray = [NSArray array];
    
    if (del.selectedHouseImages.count) {
        resultArray = [self checkImageRepeat:willAddImages];
    }else{
        resultArray = willAddImages;
    }
    
    
    
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:[self indexPathOfNewlyAddedAssets:resultArray]
                          withRowAnimation:UITableViewRowAnimationBottom];
    
    [del.selectedHouseImages addObjectsFromArray:resultArray];
    [self.tableView endUpdates];
}

#pragma mark 转化indexPath方法
- (NSArray *)indexPathOfNewlyAddedAssets:(NSArray *)array
{
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    
    for (NSInteger i = del.selectedHouseImages.count; i < del.selectedHouseImages.count + array.count ; i++)
        [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    
    return indexPaths;
}

#pragma mark 图片数组查重
-(NSArray *)checkImageRepeat:(NSArray *)assets{
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    
    //循环检查图片是否有重复的
    for (int i = 0; i < assets.count; i++) {
        if (![del.selectedHouseImages containsObject:assets[i]]) {//当图片不在数组中时，添加
            [tempArray addObject:assets[i]];
        }
    }
    return  tempArray;
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return del.selectedHouseImages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"imageCell";
    BWJImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    //将图片数组中的NSData对象取出来，先转换成image，再赋给cell上的image
    UIImage *image = [UIImage imageWithData:del.selectedHouseImages[indexPath.row]];
    cell.houseImageView.image = image;
    
    return cell;
}

#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}

#pragma mark 选中某个cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.editing) {
        return;
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark 修改删除按钮标题
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

@end










